#include "func.h"
#include "output.h"
#include "str.h"

#define NARG 16

int getcmd(char* buf, int n)
{
    char c;
    int i, cnt;

    printf("# ");
    memset(buf, 0, n);
    
    for(i=0; i<n; i++) {
        cnt = read(0, &c, 1);
        if(cnt != 1) break;
        if(c == '\n' || c == '\r') break;
        buf[i] = c;
    }
    buf[i] = '\0';

    if(buf[0] == '\0') return -1; // EOF
    else return 0;                // 正常读入
}

// 以空格为分割,将buf中的一段读入dst
// 如果buf没读完 返回剩余的buf
// 如果读完了 返回NULL
char* getstr(char* buf, char** dst)
{
    int id = 0;
    *dst = NULL;

    while (buf[id] == ' ') id++;
    if(buf[id] == '\0')
        return NULL;

    *dst = &buf[id];
    while (buf[id] != ' ' && buf[id] != '\0') id++;

    if(buf[id] == '\0')
        return NULL;

    buf[id] = '\0';

    return buf + id + 1;
}

void runcmd(char* buf)
{
    char *path;
    char *argv[NARG];

    // 获取path
    buf = getstr(buf, &path); 
    if(buf == NULL) goto end;

    // 获取argv
    for(int i=0; i<NARG; i++) {
        buf = getstr(buf, &argv[i]);
        if(buf == NULL) goto end;
    }

end:
    if(path != NULL) {
        int ret = execve(path, argv, NULL);
        if(ret < 0) printf("fail to execve\n");
        else printf("success to execve\n");
    } else {
        printf("runcmd: illegal exec\n");
    }
}

int main(void)
{
    static char buf[128];    
    int ret, pid;
    printf("shell is start\n");
    while(1) {
        ret = getcmd(buf, 128);
        if(ret < 0) break;
        pid = fork();
        if(pid < 0) {
            printf("fail to fork\n");
            while(1);
        }        
        if(pid == 0) { // 新的进程
            runcmd(buf);
        } else { // 旧的进程
            wait(NULL);
        }
    }
    return 0;   
}